'use strict'

$(() => {
    $.get('http://localhost:5600/blog',(data)=>{
        listData(data.data.rows);
    })
    
})
function btnFind(){
    let keyword=$('#keyword').val();
    $.get(`http://localhost:5600/blog?keyword=${keyword}`,(data)=>{
        $('.blogs').remove();
        listData(data); 
    })
}
function btnAdd(){
    location.href='./addOrEidt.html'
}
function btnEidt(id){
    location.href=`./addOrEidt.html?id=${id}`
}

function btnRemove(id){
    if (confirm('确认删除？')) {
        $.ajax({
            type:"delete",
            url:`http://localhost:5600/blog/${id}`,
            success:(res)=>{
                console.log(res);
                if (res.code===1000) {
                    alert(res.msg)
                    $(`[key=${id}]`).remove();
                }else{
                    alert(res.msg)
                }
            }
        })
    }
}

function listData(data) {
    data.forEach(item => {
        let html = `
        <tr class="blogs" key="${item.id}">
            <td>${item.id}</td>
            <td>${item.title}</td>
            <td>${item.abstract}</td>
            <td>${item.body}</td>
            <td>${item.CategoryName}</td>
            <td>${item.author}</td>
            <td>${item.createdAt}</td>
            <td>
                <input type="button" value="编辑" onclick="btnEidt(${item.id})">
                <input type="button" value="删除" onclick="btnRemove(${item.id})">
            </td>
        </tr>
        `
        $('#tbData').append(html);
    });


}